//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;

import org.prx.prp.utility.DatabaseAdapter;

import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
//TODO : Cleanup mechanism. Possibly cleanup if a image has been retrieved 3 months before. Discuss other methods
public class ImageCacheManager {
	private static ImageCacheManager imageCacheManager;

	private ImageCacheManager() {
		try {
			DatabaseAdapter
					.createTable("CREATE TABLE IF NOT EXISTS IMAGECACHE (URL TEXT PRIMARY KEY,data BLOB,retrieved_at DOUBLE);");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static ImageCacheManager getInstance() {
		if (imageCacheManager == null)
			imageCacheManager = new ImageCacheManager();
		return imageCacheManager;
	}

	public Bitmap getBitmapFromURL(String src, long updatedAfter) throws IOException{
		Bitmap b = null;
		Cursor c = DatabaseAdapter.executeQuery(
				"SELECT * FROM IMAGECACHE WHERE URL=?", new String[] { src });
		c.moveToFirst();
		if (c.isAfterLast()) {
			b = downloadAndStoreBitmap(src);
		} else if (c.getLong(c.getColumnIndex("retrieved_at")) > updatedAfter) {
			b = getBitmapfromByteArray(c.getBlob(c.getColumnIndex("data")));
		} else {
			DatabaseAdapter.deleteRecord("IMAGECACHE",new String[]{"URL"},new String[]{"\""+src+"\""});
			b = downloadAndStoreBitmap(src);
		}
		c.close();
		return b;
	}

	private byte[] getBitmapAsByteArray(Bitmap bitmap) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();		
		bitmap.compress(CompressFormat.PNG, 0, outputStream);		
		return outputStream.toByteArray();
	}

	private Bitmap downloadAndStoreBitmap(String url) throws IOException{
		final ContentValues params = new ContentValues();
		Calendar cal = Calendar.getInstance();
		Bitmap b = downloadImage(url);
		byte[] data = getBitmapAsByteArray(b);
		
		long currentTime = (cal.getTime().getTime()/1000);
		
		params.put("url", url);
		params.put("data", data);
		params.put("retrieved_at", currentTime);
		DatabaseAdapter.insertRecord("IMAGECACHE", params);
		return b;

	}

	private Bitmap getBitmapfromByteArray(byte[] bitmapData) {
		
		ByteArrayInputStream inputStream = new ByteArrayInputStream(bitmapData,
				0, bitmapData.length);
		return BitmapFactory.decodeStream(inputStream);
	}

	private Bitmap downloadImage(String src) throws IOException{
		
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);
			if(myBitmap==null)
				throw new IOException();
			return myBitmap;		
	}

}
